<?php
declare (strict_types=1);

namespace app\index\service;

use app\index\model\AcceptRecord;
use app\index\model\Configuration;
use app\index\model\IntegralOrder;
use app\index\model\IntegralOrderCommodity;
use app\index\model\LotteryLog;
use app\index\model\LotteryLogistics;
use app\index\model\Order;
use app\index\model\OrderCommodity;
use app\index\model\ShopAssistant;
use app\index\model\User;
use app\index\model\WechataQr;
use app\index\util\Redis;
use think\Exception;
use think\facade\Db;
use think\model\Relation;

class AcceptService
{

    private $order;

    private $redis;

    private $assistant;

    public function __construct()
    {
        global $user;
        $user = User::find($user['id']);
        $storeId = request()->param("store");
        $url = request()->action();
        $lottery_bool = $url !== 'LotteryGoodsList' && $url !== 'LotteryConfirm';
        $shop_bool = $url !== 'integralOrderList' && $url !== 'integralOrderConfirm';
        if ($url !== 'integralOrderList' && $url !== 'LotteryGoodsList' && $url !== "wxaQr") {
            $this->assistant = ShopAssistant::with(['store'])->where(
                [
                    //'merchant_id' => $this->order->merchant_id,
                    'user_id' => $user->id,
                    'store_id' => $storeId
                ])->find();
            if (!$this->assistant)
                throw new Exception("您无权查看核销该订单", HTTP_NOTACCEPT);
        }
        if ($url !== "wxaQr" && $lottery_bool && $shop_bool) {
            $orderId = request()->param("order");
            $userId = request()->param("user");
            $this->order = Order::withoutGlobalScope(['userId'])
                ->whereNotIn('status', [1, 4, 6])
                ->where(['user_id' => $userId])
                ->find($orderId);
            if (!$this->order)
                throw new Exception("订单状态不支持核销", HTTP_NOTACCEPT);
        }
        $this->redis = Redis::getInstance();
    }


    public function index($data)
    {
        $ids = explode(',', urldecode($data['ids']));

        $list = OrderCommodity::where(
            [
                'id' => $ids,
                'order_id' => $data['order'],
                'store_id' => $data['store'],
                'type' => 2,
                'status' => 2
            ])
            ->field(['id', 'count', 'commodity_id', 'sku_id', 'status', 'type'])
            ->with(
                [
                    'commodity' => function (Relation $query) {
                        $query->bind(['commodity_name' => 'name', 'master']);
                    },
                    'sku' => function (Relation $query) {
                        $query->bind(['pvs_value']);
                    },
                ]
            )
            ->select();
        if (!$list)
            throw new Exception("商品不存在");
        $list = $list->toArray();
        $diffIds = array_diff($ids, array_column($list, 'id'));
        $diffList = OrderCommodity::where(
            [
                'id' => $diffIds,
                'order_id' => $data['order'],
                'type' => 2,
            ])
            ->field(['id', 'count', 'commodity_id', 'sku_id', 'status', 'type'])
            ->with(
                [
                    'commodity' => function (Relation $query) {
                        $query->bind(['commodity_name' => 'name', 'master']);
                    },
                    'sku' => function (Relation $query) {
                        $query->bind(['pvs_value']);
                    },
                ]
            )
            ->select();
        if ($diffList)
            $diffList->toArray();
        $attach = Db::name("order_commodity_attach")->where('order_id','IN', $ids)->select()->toArray();
        return [
            HTTP_SUCCESS, [
                'order_no' => $this->order->order_no,
                'store' => $data['store'],
                'user' => $data['user'],
                'list' => $list,
                'diffList' => $diffList,
                'attach' => $attach
            ]
        ];
    }


    public function confirm(array $data)
    {
        $ids = $data['ids'];

        $list = OrderCommodity::where(
            [
                'id' => $ids,
                'order_id' => $data['order'],
                'store_id' => $data['store'],
                'type' => 2,
                'status' => 2
            ])
            ->field(['id', 'commodity_id', 'sku_id', 'status', 'type', 'count'])
            ->with(
                [
                    'commodity' => function (Relation $query) {
                        $query->bind(['commodity_name' => 'name', 'master', 'sell_price']);
                    },
                    'sku' => function (Relation $query) {
                        $query->bind(['pvs_value']);
                    },
                ]
            )
            ->select();
        if (!$list) {
            return [HTTP_NOTACCEPT, "订单有商品不能核销"];
        }

        $list = $list->toArray();

        if (count($list) !== count($ids)) {
            return [HTTP_NOTACCEPT, "订单有商品不能核销"];
        }

        if ($this->redis->has(checkRedisKey('VERIFICATION_' . $data['order']))) {
            $verificationIds = $this->redis->get(checkRedisKey('VERIFICATION_' . $data['order']));
            $intersect = array_intersect($ids, $verificationIds);
            if (!$intersect)
                return [HTTP_NOTACCEPT, "订单有商品正在核销,请稍后"];
            $merge = array_merge($ids, $verificationIds);
            $this->redis->set(checkRedisKey('VERIFICATION_' . $data['order']), $merge, 0);
        } else {
            $this->redis->set(checkRedisKey('VERIFICATION_' . $data['order']), $ids, 0);
        }
        OrderCommodity::update(['status' => 7,'receiving_time' => time()], ['id' => $ids, 'status' => 2]);

        //修改订单状态
        $model = OrderCommodity::where(['order_id' => $data['order'], 'status' => 2])->find();
        if (!$model)
            Order::withoutGlobalScope(['userId'])->where(['id' => $data['order']])->update(['status' => 8]);
        $verificationIds = $this->redis->get(checkRedisKey('VERIFICATION_' . $data['order']));
        $diff = array_diff($verificationIds, $ids);
        empty($diff) ?
            $this->redis->delete(checkRedisKey('VERIFICATION_' . $data['order'])) :
            $this->redis->set(checkRedisKey('VERIFICATION_' . $data['order']), $diff, 0);
        $commission = new CommissionService();
        $commission->settlement(Db::name('order')->where('id', $data['order'])->find());

        //创建记录
        $acceptCommodityData = [];
        foreach ($list as $index => $item) {
            $acceptCommodityData[] = [
                'commodity' => $item['commodity_name'],
                'pvs_value' => $item['pvs_value'] ?? "",
                'sell_price' => $item['sell_price'],
                'master' => $item['master'],
                'count' => $item['count'],
            ];
        }

        global $mid;
        $acceptData = [
            'mall_id' => $mid,
            'merchant_id' => $this->order->merchant_id,
            'user_id' => $this->order->user_id,
            'order_no' => $this->order->order_no,
            'commodity' => $acceptCommodityData,
            'assistant' => $this->assistant->serial_num,
            'assistant_user_id' => $this->assistant->user_id,
            'store' => $this->assistant->store->name,
            'accept_time' => date('Y-m-d H:i:s')
        ];

        AcceptRecord::create($acceptData);

        return [HTTP_SUCCESS, "核销成功"];

    }

    public function wxaQr($wxa)
    {
        global $user;
        $qrData = WechataQr::where(['wea_key' => $wxa])->value('qr_data');
        $json = json_decode($qrData);
        $check = ShopAssistant::with(['store'])->where(
                [
                    //'merchant_id' => $this->order->merchant_id,
                    'user_id' => $user->id,
                    'store_id' => $json->store
                ])->find();
        if (!$check) {
            throw new Exception("您无权查看核销该订单", HTTP_NOTACCEPT);
        }
        return [HTTP_SUCCESS, $qrData];
    }


    public function LotteryGoodsList(int $ids){
        $list = LotteryLog::where('id',$ids)
            ->with(['Logistics','prize'])
            ->select();
        return [HTTP_SUCCESS,$list];
    }

    public function LotteryConfirm(int $ids){
        global $mid;
        $logistics = LotteryLogistics::where('lottery_log_id',$ids)->find();
        $logistics->save(['status' => 3]);
        $commodity = LotteryLog::with(['prize'])->find($ids);
        AcceptRecord::create([
            'mall_id' => $mid,
            'merchant_id' => 0,
            'order_no' => $logistics->order_no,
            'user_id' => $logistics->user_id,
            'assistant' => $this->assistant->serial_num,
            'assistant_user_id' => $this->assistant->user_id,
            'store' => $this->assistant->store->name,
            'commodity' => $commodity->prize->commodity,
            'accept_time' => now(),
            'type' => 2
        ]);
        return [HTTP_SUCCESS,'成功'];
    }

    public function IntegralOrderList(int $ids){
        $order = IntegralOrder::where('id',$ids)->with(['orderCommodity' => function($sql){
            $sql->with(['goods','sellPrice','pvsValue']);
        },'store'])->select();
        return [HTTP_SUCCESS,$order];
    }

    public function IntegralOrderConfirm(int $ids){
        global $mid;
        $integral_order = IntegralOrder::find($ids);
        $integral_order->save(['status' => 3]);
        $integral_order_commodity = IntegralOrderCommodity::where('order_id',$ids)->with(['goods_info'])->find();
        $integral_order_commodity->save(['status' => 3]);
        AcceptRecord::create([
            'mall_id' => $mid,
            'merchant_id' => 0,
            'user_id' => $integral_order->user_id,
            'order_no' => $integral_order->order_no,
            'commodity' => json_encode($integral_order_commodity->goods_info),
            'assistant' => $this->assistant->serial_num,
            'assistant_user_id' => $this->assistant->user_id,
            'store' => $this->assistant->store->name,
            'accept_time' => now(),
            'type' => 3
        ]);
        return [HTTP_SUCCESS,'成功'];
    }
}
